package com.xiaozhengkeji.sc.oauth2;

import com.xiaozhengkeji.sc.bean.ResponseBean;
import com.xiaozhengkeji.sc.pojo.UserPoJo;
import com.xiaozhengkeji.sc.service.UserService;
import com.xiaozhengkeji.sc.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.LinkedHashMap;

@Slf4j
@RestController
public class OAuth2Api {
    @Autowired
    private UserService userService;


    @GetMapping("/out")
    public void out(@RequestParam("token") String token) {
        if (userService.isToken(token)){
            String userName = JWTUtil.getUsername(token);
            userService.outToken(userName);
        }
    }

    @GetMapping("/info")
    public UserPoJo info(@RequestParam("token") String token) {
        if (userService.isToken(token)){
            return userService.getUser(JWTUtil.getUsername(token));
        }
        return null;
    }

    @PostMapping("/login")
    public ResponseBean login(@RequestParam("username") String username,
                              @RequestParam("password") String password) {

        UserPoJo userPoJo = userService.getUser(username);
        if (userPoJo == null) {
            return new ResponseBean(401, "登陆失败!", "用户名不存在!");
        }
        if (userPoJo.getPassword().equalsIgnoreCase(password)) {
            HashMap<String,Object> re = new LinkedHashMap<>();
            String token = JWTUtil.sign(username, password);
            userService.upToken(token);
            re.put("token", token);
            return new ResponseBean(200, "登陆成功!", re);
        }
        return new ResponseBean(401, "登陆失败!", "用户密码错误!");
    }

    @PostMapping("/register")
    public ResponseBean register(@RequestParam("username") String username,
                                 @RequestParam("password") String password) {
        UserPoJo userPoJo = new UserPoJo();
        userPoJo.setRid(1);
        userPoJo.setUsername(username);
        userPoJo.setPassword(password);
        if (userService.regUser(userPoJo)){
            return new ResponseBean(200, "处理完成!", "注册成功!");
        }else {
            return new ResponseBean(412, "注册失败!", "注册失败!");
        }
    }
}
